package com.xiaoma.myaudience.biz.task;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;

import com.xiaoma.myaudience.R;
import com.xiaoma.myaudience.biz.model.UserAccount;
import com.xiaoma.myaudience.biz.util.Constant;
import com.xiaoma.myaudience.util.HttpUtils;
import com.xiaoma.myaudience.util.Logger;
import com.xiaoma.myaudience.util.task.BaseDataAsyncTask;

/**
 * 登陆
 * @author xali
 *
 */
public class LoginTask extends BaseDataAsyncTask<UserAccount, Void, Map<String,Object>> {
    private final static String TAG = "VideodetailInfoTask";
    /**
     * {@inheritDoc}
     * 
     * @param context
     * @param taskType
     * @param callback
     */
    public LoginTask(Context context, int taskType, DataAsyncCallback callback) {
        super(context, taskType, callback);
    }
    
    @Override
    protected Map<String,Object> doInBackground(UserAccount... params) {
    	Map<String,Object> result = new HashMap<String,Object>();
    	LoginStatus loginStatus = null;
		//String cookie = "";
		boolean loginsuccess = false;
        if(params[0] == null){ 
        	result.put(Constant.LOGIN_ISLOGIN, false);
        }else{
	        UserAccount userAccount = params[0];   
	        String url = Constant.URL_LOGIN;
	        Logger.i("url is "+url);
	        try {
	        	loginStatus = new LoginStatus();
	          
	        	List<NameValuePair> loginParams = new ArrayList<NameValuePair>();
	        	loginParams.add(new BasicNameValuePair(UserAccount.USERNAME, userAccount.mAccount));
	        	loginParams.add(new BasicNameValuePair(UserAccount.PASSWORD, userAccount.mPassword));
	        	loginParams.add(new BasicNameValuePair("status", "2"));
	        	HttpResponse httpResponse = HttpUtils.doHttpExecute(getHttpClient(), url, loginParams, null, HttpUtils.POST, "GBK");
	        	/**JSONObject jsonarray = HttpUtils.getHttpJSONObjectResult(getHttpClient(), url, loginParams, HttpUtils.POST);
	        	if (jsonarray != null) {
        			Map<String, Object> objMap = ModelUtils.json2Map(jsonarray);
        			if (objMap != null) {
        				result = ModelUtils.getMapValue(objMap, ActivityInfoModel.PARAM_DATA);
					}
				}
	        	**/
	        	
	        	if (httpResponse != null && httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
	        		String responseStr = EntityUtils.toString(httpResponse.getEntity());
	        		result.put("json", responseStr);
					String code = "";
					if(responseStr!=null){
						try {
							JSONObject jsonobj = new JSONObject(responseStr);
							code=jsonobj.get("code").toString();
							result.put("data", jsonobj.get("data").toString());
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
					
					if(!code.equals("0")){
						//Tips("网站没有响应");测试用成功
						result.put(Constant.LOGIN_ISLOGIN, false);
					}else{
						result.put(Constant.LOGIN_ISLOGIN, true);
						Header[] headers = httpResponse.getAllHeaders();
						int isok = 0;
						for (int index = 0; index < headers.length; index++) {
							
							if ("Set-Cookie".equals(headers[index].getName())) {
								
								String value = headers[index].getValue();
								String[] values = value.split(";");
								for (int i = 0; i < values.length; i++) {
									String[] vss = values[i].split("=");
									if (Constant.LOGIN_COOKIE1.equals(vss[0])&&!"deleted".equals(vss[1])) {
										result.put(Constant.LOGIN_COOKIE1, vss[1]);
										//store expires date
										result.put(Constant.LOGIN_EXPIRESDATE,values[i+1].split("=")[1] );
									}
									if (Constant.LOGIN_COOKIE2.equals(vss[0])&&!"deleted".equals(vss[1])) {
										result.put(Constant.LOGIN_COOKIE2, vss[1]);
									}
								}
								
							}
						}
						Logger.e("isok: "+isok);
						loginsuccess = true;
					}
					if(loginsuccess){
						loginStatus.mCodeStatus = 1;
						loginStatus.mMessage = mContext.getResources().getString(R.string.str_login_success);	
					}else {
						loginStatus.mCodeStatus = -1;
						loginStatus.mMessage = mContext.getResources().getString(R.string.str_account_or_password_is_invalid);				
					}
	        	
	        	}else if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_GATEWAY_TIMEOUT) {
	        		loginStatus.mCodeStatus = -1;
	        		loginStatus.mMessage = "code:" + HttpStatus.SC_GATEWAY_TIMEOUT;
				} else if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_FOUND) {
					loginStatus.mCodeStatus = -1;
					loginStatus.mMessage = "code:" + HttpStatus.SC_NOT_FOUND;
				} else if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_BAD_GATEWAY) {
					loginStatus.mCodeStatus = -1;
					loginStatus.mMessage = "code:" + HttpStatus.SC_BAD_GATEWAY;
				} else if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_SERVICE_UNAVAILABLE) {
					loginStatus.mCodeStatus = -1;
					loginStatus.mMessage = "code:" + HttpStatus.SC_SERVICE_UNAVAILABLE;
				} else {
					loginStatus.mCodeStatus = -1;
					loginStatus.mMessage = mContext.getResources().getString(R.string.str_account_or_password_is_invalid);				
				}
	        } catch (Exception e) {
	            Logger.e(TAG, "doInBackground error!!!", e);
	            loginFail();
	            return null;
	        } finally {
	            closeHttpClient();
	        }
        }
        
    	return result;
    }
    
    private void loginFail(){
    	
    	Logger.e("login fail, clear all user infomation.");
    	
    	ContentResolver r = mContext.getContentResolver();
    	ContentValues values = new ContentValues();
    	values.put(UserAccount.ISLOGIN, "0");
    	String where = UserAccount.ISLOGIN + "='1'"; 
//    	r.update(UserAccountDbHelper.getUri(), values, where, null);
        
    }
    
    public class LoginStatus{
    	/**登陆标示1为登陆成功 ，其他为登陆失败*/
    	public int mCodeStatus;
    	/**登陆信息*/
    	public String mMessage;
    }
}
